(function () {
    'use strict';
    /**
     *
     * 用户管理 控制器
     *
     */
    var usersModel = angular.module('zhxProject.userInfo', ['datePicker']);
    /**
     * 用户信息列表
     */
    

    usersModel.controller('userInfoController', function ($rootScope,$scope, ngDialog, notifyService, gridService, submitService,$filter) {

        $scope.userParameters = {pageSize: 10, pageNum: 1};

        $scope.startIndex = 1;
        $scope.i18n = $rootScope.i18n;

        /**
         * 打开新增用户新按钮
         */
        $scope.addNew = function () {
            ngDialog.open({
                templateUrl: 'js/modules/auth/user/user-add.html',
                scope: $scope,
                controller: 'userAdd',
                size: 600
            });
        };
        /**
         * 修改选中数据
         */
        $scope.modify = function () {
            var checked = $scope.getCheckedItems();
            if (!checked.length || checked.length > 1) {
                notifyService.notify($scope.i18n.message_grid_check,   'warn');
            } else {
                $scope.user = checked[0];
                ngDialog.open({
                    templateUrl: 'js/modules/auth/user/user-edit.html',
                    scope: $scope,
                    controller: 'userEdit',
                    size: 600
                });
            }
        }
        /**
         * 删除选中数据
         */
        $scope.removeList = function () {
            var checked = $scope.getCheckedIds();

            if (!checked.length) {
                notifyService.notify($scope.i18n.message_grid_check,   'warn');
            } else {
                submitService.submit('SysUser/remove/' + checked).then(function(data){
                    notifyService.showMessage(data);
                    $scope.initTableList();
                });
            }
        }

        /**
         * 查询按钮使用
         */
        $scope.showSearch = function () {
            ngDialog.open({
                templateUrl: 'js/modules/auth/user/user-search.html',
                scope: $scope,
                controller: 'userSearch',
                size: 600
            });
        };
        /**
         * 用户授权
         */
        $scope.authorize = function () {
            
            $scope.checkUserList = $scope.getCheckedItems();
            if (!$scope.checkUserList.length || $scope.checkUserList.length > 1) {  
            	notifyService.notify($scope.i18n.message_grid_check, 'warn');
            } else {
                ngDialog.open({
                    templateUrl: 'js/modules/auth/user/user-authorize.html',
                    scope: $scope,
                    controller: 'userAuthorize',
                    size: 600
                });
            }
      };

        /**
         *
         * ZHX-GRID options
         *
         * @param gridData          获取的数据对象         require
         * @param scope             当前控制器的作用域   require
         * @param columnDefs        字段展示信息          require
         * @param checkModel        是否显示checkbox    optional
         * @param sorter            如果该表格有排序字段，则为排序的回调方法 optional
         * @param flexHeight        设置该高度后，表格会自动将屏幕高度减此高度设置为一个动态高度，保证表格始终全屏 optional
         * @param height            设置一个固定高度. 如果表格没有设置任何高度，则高度将在css中设置为auto optional
         * @param paginationConf    分页设置 optional
         *
         * ** name == zhxRowNumber 的字段可以自动生成一列序号
         */
        $scope.gridOptions = {
            gridData: [],
            scope : $scope,
            columnDefs: [
                { displayName: $scope.i18n.grid_rowNumber, name: "zhxRowNumber" },
                { displayName: $scope.i18n.user_userAccount, name: "userAccount", width:120, enableSorting: true},
                { displayName: $scope.i18n.user_userName, name: "userName", width:150, enableSorting: true},
                {
                    displayName: $scope.i18n.user_userCreateTime,
                    name: "userCreateTime",
                    width:200,
                    /**
                     * $filter('filter')(array, expression, comparator)
                     * 过滤器具体用法请参考AngularJS API 关于 $filter 服务的部分
                     *
                     * 如果是自定义的简单过滤器，只最要传递一个字符串即可，如果是复杂过滤器带表达式等，需要传递一个对象
                     * @param name 过滤器名称
                     * @param params 过滤器需要的参数数组，对应AngularJS的文档，为 [ expression, comparator ];
                     */
                    filter :{
                        name : 'date',
                        params : ['yyyy-MM-dd HH:m:ss']
                    }
                    /**
                     * render 可以独立渲染单元格内容，接收两个参数
                     * @param value 当前单元格值
                     * @param row  行对象， 这里限于参数无法传递对象，因此这里为 JSON string,根据使用可以通过 JSON.parse()转为JSON对象
                     *
                     * 这里注释表示可以自行使用过滤器服务来实现日期的格式化
                     */
                    //renderer:function(value,row){
                    //    var strDate =  $filter('date')(value,'yyyy-MM-dd');
                    //    return "<span style='color:red'>" + strDate + "</span>";
                    //}
                },  
                { displayName: $scope.i18n.user_userEnable, name: "userEnable", width:100, filter: 'userStatus', enableSorting: true},
                {displayName: $scope.i18n.user_userOrgName, name: "userOrgName", width:120},
                {
                    displayName: $scope.i18n.user_userOperation,
                    width:150,
                    renderer : function(value, row){
                        return "<a href='#' ng-click='resetPassword("+ value +")'>"+$scope.i18n.user_resetPassword+"</a>" 
                            
                    }
                },  
                {displayName: $scope.i18n.user_email, name: "email"},
                {displayName: $scope.i18n.user_userTelephone, name: "userTelephone"},
                {displayName: $scope.i18n.user_userMobile, name: "userMobile"}
             
            ],
            checkModel: true,
            flexHeight : 180,
            //height : 500,
            sorter: function (order, desc) {
                $scope.userParameters.orderBy = order;
                $scope.userParameters.descOrAsc = desc;
                $scope.initTableList();
            },
            paginationConf: {
                currentPage: 1,
                itemsPerPage: 10,
                perPageOptions: [10, 20, 30, 40, 50, 100, 200, 300],
                onChange: function () {
                    $scope.userParameters.pageSize = $scope.gridOptions.paginationConf.itemsPerPage;
                    $scope.userParameters.pageNum = $scope.gridOptions.paginationConf.currentPage;
                    $scope.startIndex = ($scope.gridOptions.paginationConf.currentPage - 1) * $scope.gridOptions.paginationConf.itemsPerPage + 1;
                    $scope.initTableList();
                }
            }

        }

        $scope.initTableList = function(){
            /**
             * 初次加载页面加载列表数据
             */
            submitService.submit('SysUser/getPage', $scope.userParameters).
                then(function (data) {
                    $scope.gridOptions.gridData = data.list;
                    $scope.gridOptions.paginationConf.totalItems = data.total;
                });

        }
        $scope.$on('userParameters', function(event, data) {
            $scope.userParameters = data;
        });

        $scope.initTableList();

        /**
         * 定义行点击事件
         * @param data
         * @param event 这里做了一些处理，当点击首列中的label和checkbox时，通过stopPropagation()方法来阻止事件的传播。因为点击checkbox时
         *              不能触发该事件
         */
        $scope.showDetail = function (data, event) {
            //console.log(data);
        }

        $scope.resetPassword = function (data) {
            $scope.modalOptions = {
                headerText : $scope.i18n.message_resetPassword_title,
                bodyText   : $scope.i18n.message_resetPassword_content
            }
            ngDialog.open({
                templateUrl : 'tpl/window.html',
                size : 350,
                scope : $scope
            });
            $scope.ok = function () {
                   //data = {userPassword:"123"}
                    data.userPassword = '123';
                    submitService.submit('SysUser/edit', data);
                     ngDialog.close();
                }
        }

        $scope.approve = function (data) {
        	
        	$scope.userApprove = data;
            ngDialog.open({
          	templateUrl: 'js/modules/auth/user/user-approve.html',
              scope: $scope,
              controller: 'userApprove',
              size: 800
          });
        }

    });

    usersModel.controller('userApprove', function ($scope, ngDialog, notifyService, submitService, $http) {
    	
    	$scope.approveStatusList = [{id:0, name:'--请选择--'}, {id:1, name:'通过'}, {id:2, name:'不通过'}];
        $scope.ok = function () {
            delete $scope.userApprove.ngDialogId;
            submitService.submit('SysUser/userApprove', $scope.userApprove).then(function(data){
                ngDialog.close();
                $scope.initTableList();
                notifyService.showMessage(data);
            });
        }
        $scope.cancel = function () {
            ngDialog.close();
        }
    });
    
    /**
     * 用户新增数据 控制器
     * @$modalInstance  模态框引用
     * @gridService
     */
    usersModel.controller('userAdd', function ($scope, ngDialog, notifyService, submitService, $http) {
        //模型对象初始值设置
//        $scope.userAdd = {userGender: "男", userEnable: "1", userPassword: '123'};
    	$scope.userAdd={};
        $scope.ok = function () {
            delete $scope.userAdd.ngDialogId;
            submitService.submit('SysUser/add', $scope.userAdd).then(function(data){
                ngDialog.close();
                $scope.initTableList();
                notifyService.showMessage(data);
            });
        }
        /**
         * 打开新增用户新按钮
         */
        $scope.cancel = function () {
            ngDialog.close();
        }
        //选择所属机构
        $scope.selectOrgs = function () {
            ngDialog.open({
                templateUrl: 'js/modules/auth/user/user-org.html',
                scope: $scope,
                data: $scope.userAdd,
                controller: 'userOrg',
                size: 400
            }).closePromise.then(function (data) {
            	    if(data.value){
            	    
            	    //给userAdd赋予组织机构信息
            	    $scope.userAdd.userOrgUuid = data.value[0].id;
            	    //显示使用
            	    $scope.userAdd.userOrgName = data.value[0].name;
            	    //console.log(data.value);
            	    }	
                });
        };


    });
//用户角色授权
    usersModel.controller('userAuthorize', function ($scope, ngDialog, notifyService, submitService, gridService, $http) {        
        var roleParameters = {pageSize: 10, pageNum: 1, userId: $scope.checkUserList[0].id};
        $scope.gridOptions = {
                gridData: [],
                scope : $scope,
                checkModel: true,  
                columnDefs: [
                    { displayName: $scope.i18n.grid_rowNumber, name: "zhxRowNumber" },
                    { displayName: $scope.i18n.role_rolesName, name: "rolesName"},
                    { displayName: $scope.i18n.role_rolesDesc, name: "rolesRemark"},
                    /*{ displayName: $scope.i18n.role_rolesEnable, name: "rolesEnable", filter: 'userStatus'},*/
                    {
                        displayName: $scope.i18n.role_rolesCreateTime,
                        name: "rolesCreateTime",
                        width:200,
                        filter :{
                            name : 'date',
                            params : ['yyyy-MM-dd HH:m:ss']
                        }
                    
                    } 
                ],
                flexHeight : 400,
                sorter: function (order, desc) {
                    $scope.roleParameters.orderBy = order;
                    $scope.roleParameters.descOrAsc = desc;
                    $scope.initTableList();
                },
                paginationConf: {
                    currentPage: 1,
                    itemsPerPage: 10,
                    perPageOptions: [10, 20, 30, 40, 50, 100, 200, 300],
                    onChange: function () {
                        $scope.roleParameters.pageSize = $scope.gridOptions.paginationConf.itemsPerPage;
                        $scope.roleParameters.pageNum = $scope.gridOptions.paginationConf.currentPage;
                        $scope.initTableList();
                    }
                }
            }
        
        $scope.initTableList = function () {
        submitService.submit('SysRole/getCheckPage', roleParameters).
            then(function (data) {
                $scope.gridOptions.gridData = data.list;
                $scope.gridOptions.paginationConf.pageNum = data.total;
            });
        }
        $scope.initTableList();
        $scope.ok = function () {
            var parameter = {
                checkUserList: JSON.stringify($scope.checkUserList),
                checkedRoleIds: JSON.stringify($scope.getCheckedIds())
            };
            submitService.submit('SysUser/authorize', parameter).then(function(data){
            	 ngDialog.close();
            });
        }

  
        /**
         * 打开新增用户新按钮
         */
        $scope.cancel = function () {
            ngDialog.close();
        }

    });


    usersModel.controller('userOrg', function ($scope, ngDialog, gridService, submitService, ngNotify, $http) {

        var orgSetting = {
            check: {
                enable: true,
                chkStyle: "radio",
                radioType: "all"
            },

            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        function zTreeBeforeClick(treeId, treeNode, clickFlag) {
            return !treeNode.isParent;//当是父节点 返回false 不让选取
        };
        var tree = {};
        var user = {userId: null};
        submitService.submit("SysUser/getUserOrgTree", user)
            .then(function (data) {
                //console.log($scope.userAdd);
                //查询反选判断 ;
                var orgId = $scope.ngDialogData.userOrgUuid;
                for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].id == orgId) {
                        data.data[i].checked = true;
                    }
                }
                tree = $.fn.zTree.init($("#userOrgTree"), orgSetting, data.data);
            });

        $scope.ok = function () {
            $scope.nodes = tree.getCheckedNodes();
            $scope.closeThisDialog($scope.nodes);
        }
        /**
         * 关闭按钮
         */
        $scope.cancel = function () {
            $scope.closeThisDialog();
        }
    });


    /**
     * 用户信息编辑
     */
    usersModel.controller('userEdit', function ($scope, ngDialog,notifyService, ngNotify, submitService, $http) {

        $scope.ok = function () {
            delete $scope.user.ngDialogId;
            submitService.submit('SysUser/edit', $scope.user).then(function(data){
                ngDialog.close();
                notifyService.showMessage(data);
                $scope.initTableList();
            });
        }
        /**
         *关闭按钮
         */
        $scope.cancel = function () {
            ngDialog.close();
        }
        //选择所属机构
        $scope.selectOrgs = function () {
            ngDialog.open({
                templateUrl: 'js/modules/auth/user/user-org.html',
                scope: $scope,
                data: $scope.user,
                controller: 'userOrg',
                size: 400
            }).closePromise.then(function (data) {
                    //给userAdd赋予组织机构信息
                    $scope.user.userOrgUuid = data.value[0].id;
                    //显示使用
                    $scope.user.userOrgName = data.value[0].name;
                    //console.log(data.value);
                });
        };


    });

    /**
     * 用户查询数据 控制器
     * @$modalInstance  模态框引用
     * @gridService
     */
    usersModel.controller('userSearch', function ($scope, ngDialog, ngNotify, $http) {
        $scope.search = function () {
            $scope.userParameters = new Object();
            if ($scope.userSearch != undefined) {
                $scope.userParameters = $scope.userSearch;
            }
            $scope.userParameters.pageSize = 10;
            $scope.userParameters.pageNum = 1;
            $scope.$emit('userParameters', $scope.userParameters);
            $scope.initTableList();
            ngDialog.close();
        }
        /**
         * 打开新增用户新按钮
         */
        $scope.cancel = function () {
            ngDialog.close();
        }

    });

    usersModel.filter("userStatus", function(){
        var i18n =  JSON.parse(localStorage.getItem("i18n"));
        return function( status ){
            switch( status ){
                case 0:
                    return i18n.status_unable;
                    break;
                case 1:
                    return i18n.status_enable;
                    break;               
                default:
                    return "";//异常状态
            }
        }
    });
    


})();
